package com.bear.richtext.type

import android.content.Context
import android.graphics.Color
import android.view.View
import android.widget.EditText
import android.widget.FrameLayout
import androidx.core.view.setMargins
import com.bear.richtext.Constant
import com.bear.richtext.utils.Tools
import org.json.JSONObject

/**
 * 标签组件
 */
class ItemTag() : RichItem() {

    companion object {
        const val CONTENT = "content" //文本内容
        const val BACKGROUND = "background" //背景图
        const val TAG = "ItemTag"
    }

    private var content: String? = null
    private var background: String? = null

    override fun toJson(): JSONObject {
        this.richView?.let {
            var jsonObject = JSONObject()
            jsonObject.put(TYPE, RichItemType.Tag)
            var attrs = JSONObject()
            attrs.put(CONTENT, content)
            attrs.put(BACKGROUND, background)
            jsonObject.put(ATTRS, attrs)
            return jsonObject
        }
        return JSONObject()
    }

    override fun parse(context: Context, jsonObject: JSONObject): View {
        try {
            this.content = jsonObject.optJSONObject(ATTRS).optString(CONTENT)
            this.background = jsonObject.optJSONObject(ATTRS).optString(BACKGROUND)
        } catch (e: Exception) {

        }
        val editText = EditText(context)
        val layoutParams = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT
        )
        layoutParams.setMargins(Constant.Default_MARGIN)
        editText.layoutParams = layoutParams
        editText.isCursorVisible = true
        editText.background = null
        this.background?.let {
            try {
                editText.setBackgroundColor(Color.parseColor(it))
            } catch (e: Exception) {
                Tools.elog(TAG, "color is error:${it}")
            }
        }
        this.content?.let {
            editText.setText(it)
        }
        return editText
    }

    constructor(context: Context, content: String, color: String) : this() {
        this.content = content
        this.background = color
        this.richView = parse(context, JSONObject())
    }

    constructor(context: Context, jsonContent: JSONObject) : this() {
        this.richView = parse(context, jsonContent)
    }

    override fun type(): RichItemType {
        return RichItemType.Tag
    }

    override fun setEditable(editable: Boolean) {
        this.richView?.apply {
            if (!editable) {
                this.setFocusable(false)
                this.isFocusableInTouchMode = false
            } else {
                this.setFocusable(true)
                this.isFocusableInTouchMode = true
            }
        }
    }
}